package com.ilxqx.framework.system.util;

import com.google.common.collect.Lists;
import com.ilxqx.framework.system.entity.anno.Excel;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 导出工具类
 * @author venus
 */
@Slf4j
public final class ExportUtils {

	/**
	 * 获取表头信息
	 * @param entityClass 实体类
	 * @return 表头
	 */
	public static List<String> extractHeaderTitles(Class<?> entityClass) {
		List<Field> fields = ReflectionUtils.getAnnotatedFields(entityClass, Excel.class);
		return fields.stream()
			.map(field -> field.getDeclaredAnnotation(Excel.class).value())
			.collect(Collectors.toList());
	}

	/**
	 * 获取数据
	 * @param entities 实体类List
	 * @return 数据
	 */
	public static <T> List<List<Object>> extractData(List<T> entities) {
		if (entities.isEmpty()) {
			return Lists.newArrayList();
		}
		List<Field> fields = ReflectionUtils.getAnnotatedFields(entities.get(0).getClass(), Excel.class);
		List<List<Object>> data = Lists.newArrayListWithExpectedSize(128);
		for (Object entity : entities) {
			List<Object> rowData = Lists.newArrayListWithExpectedSize(16);
			for (Field field : fields) {
				Object value = ReflectionUtils.getFieldValue(field, entity);
				String method = field.getDeclaredAnnotation(Excel.class).method();
				if (value == null || StringUtils.isBlank(method)) {
					// 直接调用获取值
					if (value instanceof Boolean) {
						rowData.add(((Boolean) value) ? "是" : "否");
					} else {
						rowData.add(value);
					}
					continue;
				}
				// 调用方法
				Method invokeMethod = org.springframework.util.ReflectionUtils.findMethod(value.getClass(), method);
				if (invokeMethod == null) {
					rowData.add(null);
					continue;
				}
				Object result = org.springframework.util.ReflectionUtils.invokeMethod(invokeMethod, value);
				rowData.add(result);
			}
			data.add(rowData);
		}
		return data;
	}

}
